/** @format */

import { createVNode, render, App } from 'vue';
import DialogConfirmComponent from './Index.vue';

interface DialogConfirmOptions {
  visible?: boolean;
  title?: string;
  width?: string;
  message?: string;
  type?: 'success' | 'info' | 'warning' | 'error';
  subMessage?: string;
  showIcon?: boolean;
  iconClass?: string;
  confirmButtonText?: string;
  cancelButtonText?: string;
  showCancelButton?: boolean;
  onConfirm?: () => void;
  onCancel?: () => void;
}

interface DialogConfirmInstance {
  close: () => void;
}

const DialogConfirm = (
  options: DialogConfirmOptions = {},
): DialogConfirmInstance => {
  // 创建容器
  const container = document.createElement('div');

  // 创建VNode
  const vnode = createVNode(DialogConfirmComponent, {
    ...options,
    visible: true,
    onConfirm: () => {
      try {
        // 调用用户传入的确认回调
        options.onConfirm?.();
        // 移除组件
        render(null, container);
        // 确保元素存在于DOM中才移除
        const element = document.querySelector('.dialog-confirm-overlay');
        if (element && element.parentNode) {
          element.parentNode.removeChild(element);
        }
      } catch (error) {
        console.error('Error in onConfirm callback:', error);
      }
    },
    onCancel: () => {
      try {
        // 调用用户传入的取消回调
        options.onCancel?.();
        // 移除组件
        render(null, container);
        // 确保元素存在于DOM中才移除
        const element = document.querySelector('.dialog-confirm-overlay');
        if (element && element.parentNode) {
          element.parentNode.removeChild(element);
        }
      } catch (error) {
        console.error('Error in onCancel callback:', error);
      }
    },
  });

  // 渲染组件
  render(vnode, container);

  // 确保元素存在后再添加到body
  const element = container.firstElementChild;
  if (element) {
    document.body.appendChild(container);
  } else {
    console.error(
      'DialogConfirm component rendering failed: No element was created',
    );
  }

  // 返回实例
  return {
    close: () => {
      const vm = vnode.component?.proxy;
      if (vm && typeof (vm as any).handleClose === 'function') {
        (vm as any).handleClose();
      }
      // 移除组件
      render(null, container);
      // 确保元素存在于DOM中才移除
      if (container.parentNode) {
        container.parentNode.removeChild(container);
      }
    },
  };
};

// 用于Vue插件安装
DialogConfirm.install = (app: App): void => {
  app.config.globalProperties.$dialogConfirm = DialogConfirm;
};

export default DialogConfirm;
